import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { MdArrowBack } from 'react-icons/md';
import styles from './travel.module.css';

const Travel = () => {
    const navigate = useNavigate();
    const [travelItems, setTravelItems] = useState([]);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState(1);
    const listRef = useRef(null);
    
    // 南京路附近真实景点数据
    const generateTravelData = (page, limit = 10) => {
        const nanjingRoadAttractions = [
            {
                id: 1,
                name: "南京路步行街",
                image: "https://youimg1.c-ctrip.com/target/100j12000000sfucs7907.jpg",
                description: "中国第一商业街，拥有百年历史的购物天堂，汇聚各类品牌店铺和老字号",
                price: 0,
                rating: 4.7,
                distance: 0.2,
                purchaseCount: 9876,
                location: "上海市黄浦区南京东路"
            },
            {
                id: 2,
                name: "人民公园",
                image: "https://ts1.tc.mm.bing.net/th/id/R-C.d92a07af6de225255d2563135c9d795d?rik=oAnVcMYIFXuIfw&riu=http%3a%2f%2fimg1.qunarzz.com%2ftravel%2fd7%2f1411%2f9c%2f9c58f319002c0cfa213a9cdb.jpg_r_1024x683x95_add99ea2.jpg&ehk=n8LhnQl0ef3zQvyES2FZTPHD5PNSrZF8wDESJA0va24%3d&risl=&pid=ImgRaw&r=0",
                description: "市中心的绿色氧吧，前身为跑马厅，是市民休闲放松的好去处",
                price: 20,
                rating: 4.5,
                distance: 1,
                purchaseCount: 7654,
                location: "上海市黄浦区南京西路231号"
            },
            {
                id: 3,
                name: "上海博物馆",
                image: "https://tse4-mm.cn.bing.net/th/id/OIP-C.WC9Ly5qBXTQ_n1BywKewZwHaE8?rs=1&pid=ImgDetMain",
                description: "中国古代艺术的殿堂，收藏了大量珍贵文物，了解中华文明的窗口",
                price: 70,
                rating: 4.8,
                distance: 1.2,
                purchaseCount: 8932,
                location: "上海市黄浦区人民大道201号"
            },
            {
                id: 4,
                name: "豫园商城",
                image: "https://img.pconline.com.cn/images/upload/upc/tx/itbbs/1804/24/c9/84299008_1524532378235_mthumb.jpg",
                description: "明代园林与传统商业街区的完美结合，上海城隍庙旅游区的核心",
                price: 0,
                rating: 4.6,
                distance: 3,
                purchaseCount: 9214,
                location: "上海市黄浦区安仁街218号"
            },
            {
                id: 5,
                name: "外滩",
                image: "https://ts1.tc.mm.bing.net/th/id/R-C.538f6f7e8fd062a9d8b373c18d1a054d?rik=7d0I8%2fMWWpdksA&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50029%2f0912.jpg_wh1200.jpg&ehk=6aj5%2burqJM9rVDeh2UCYMLfDIGvDWZkvXH1%2bRBKtPAc%3d&risl=&pid=ImgRaw&r=0",
                description: "上海地标性景观，万国建筑博览群与黄浦江相映成趣，夜景绝美",
                price: 0,
                rating: 4.9,
                distance: 5,
                purchaseCount: 9998,
                location: "上海市黄浦区中山东一路"
            },
            {
                id: 6,
                name: "新世界",
                image: "https://so1.360tres.com/t0112185f8bdc176af1.jpg",
                description: "上海历史悠久的综合性商场，红色尖顶是上海的地标之一",
                price: 50,
                rating: 4.3,
                distance: 8,
                purchaseCount: 6542,
                location: "上海市黄浦区南京西路2号"
            },
          
            {
                id: 9,
                name: "上海当代艺术博物馆",
                image: "https://ts1.tc.mm.bing.net/th/id/R-C.ce1bedd98b5623b4475b07b3104edfcc?rik=70qBAAy%2bJechrA&riu=http%3a%2f%2fimg0.xinmin.cn%2f2018%2f03%2f25%2f20180325095258612542.jpg&ehk=u%2bfxZOD%2fveqgKznx%2f2uAfUg1fQyD%2fiLzTeLANxfKi4A%3d&risl=&pid=ImgRaw&r=0&sres=1&sresct=1",
                description: "由发电厂改建的现代艺术展览空间，定期举办当代艺术展览",
                price: 70,
                rating: 4.7,
                distance: 20,
                purchaseCount: 3987,
                location: "上海市黄浦区花园港路200号"
            },
            {
                id: 10,
                name: "上海第一食品商店",
                image: "https://tse4-mm.cn.bing.net/th/id/OIP-C.6dGuGrU_h7C18INKf_NbBwHaEK?rs=1&pid=ImgDetMain",
                description: "创建于1936年的老字号，提供各类进口和国产食品的综合超市",
                price: 0,
                rating: 4.6,
                distance: 24,
                purchaseCount: 8765,
                location: "上海市黄浦区南京东路720号"
            },
            {
                id: 11,
                name: "上海大剧院",
                image: "https://tse3-mm.cn.bing.net/th/id/OIP-C.L9QAmPqn_MjOhhX5K54dUQHaE7?rs=1&pid=ImgDetMain",
                description: "上海文化地标，新古典主义风格的建筑，经常上演世界级演出",
                price: 180,
                rating: 4.8,
                distance: 27,
                purchaseCount: 7321,
                location: "上海市黄浦区人民大道300号"
            },
            {
                id: 12,
                name: "上海自然博物馆",
                image: "https://tse4-mm.cn.bing.net/th/id/OIP-C.T5ma143Vbyhg89vDkYZY7wHaE8?rs=1&pid=ImgDetMain",
                description: "中国规模最大的自然博物馆之一，设有丰富的展区和互动体验",
                price: 45,
                rating: 4.7,
                distance: 28,
                purchaseCount: 6589,
                location: "上海市静安区北京西路510号"
            },
            {
                id: 13,
                name: "上海杜莎夫人蜡像馆",
                image: "https://tse1-mm.cn.bing.net/th/id/OIP-C.1sjtw8JyilPTqRJoMJuFeAHaFj?rs=1&pid=ImgDetMaing",
                description: "与各国名人蜡像合影的好去处，互动性极强的旅游景点",
                price: 190,
                rating: 4.4,
                distance: 28.5,
                purchaseCount: 5462,
                location: "上海市黄浦区南京西路2-68号新世界商厦10楼"
            },
           
        ];
        
        const startIdx = (page - 1) * limit;
        const endIdx = Math.min(startIdx + limit, nanjingRoadAttractions.length);
        return nanjingRoadAttractions.slice(startIdx, endIdx);
    };
    
    // 初始加载数据
    useEffect(() => {
        setTravelItems(generateTravelData(1));
    }, []);
    
    // 下拉刷新和加载更多
    const handleScroll = () => {
        if (loading || travelItems.length >= 20) return;
        
        const scrollElement = listRef.current;
        if (!scrollElement) return;
        
        const { scrollTop, scrollHeight, clientHeight } = scrollElement;
        
        // 当滚动到底部时加载更多
        if (scrollTop + clientHeight >= scrollHeight - 50) {
            loadMore();
        }
    };
    
    const loadMore = () => {
        if (travelItems.length >= 20) return;
        
        setLoading(true);
        // 模拟网络请求延迟
        setTimeout(() => {
            const nextPage = page + 1;
            setPage(nextPage);
            setTravelItems(prev => [...prev, ...generateTravelData(nextPage)]);
            setLoading(false);
        }, 800);
    };
    
    const refresh = () => {
        setLoading(true);
        setTimeout(() => {
            setPage(1);
            setTravelItems(generateTravelData(1));
            setLoading(false);
        }, 800);
    };
    
    // 获取评分和价格的样式变体
    const getRatingVariantClass = (index) => {
        const variants = [styles.ratingVariant1, styles.ratingVariant2, styles.ratingVariant3];
        return variants[index % 3];
    };
    
    const getPriceVariantClass = (index) => {
        const variants = [styles.priceVariant1, styles.priceVariant2, styles.priceVariant3, styles.priceVariant4];
        return variants[index % 4];
    };
    
    const getAnimationDelayClass = (index) => {
        if (index < 5) {
            return styles[`animationDelay${index + 1}`];
        }
        return '';
    };
    
    return (
        <div className={styles.travelContainer}>
            <header className={styles.travelHeader}>
                <div className={styles.headerLeft}>
                    <button className={styles.backButton} onClick={() => navigate(-1)}>
                        <MdArrowBack />
                    </button>
                    <h1>南京路周边景点</h1>
                </div>
                <button className={styles.refreshButton} onClick={refresh} disabled={loading}>
                    {loading ? '刷新中...' : '刷新'}
                </button>
            </header>
            
            <div className={styles.travelList} ref={listRef} onScroll={handleScroll}>
                {travelItems.map((item, index) => (
                    <div 
                        className={`${styles.travelItem} ${getAnimationDelayClass(index)}`} 
                        key={item.id}
                    >
                        <div className={styles.travelImage}>
                            <img src={item.image} alt={item.name} />
                            <span className={`${styles.travelRating} ${getRatingVariantClass(index)}`}>
                                <i className={styles.starIcon}>★</i> {item.rating}
                            </span>
                        </div>
                        <div className={styles.travelContent}>
                            <h3 className={styles.travelName}>{item.name}</h3>
                            <p className={styles.travelDesc}>{item.description}</p>
                            <div className={styles.travelInfo}>
                                <div className={styles.travelLocation}>
                                    <i className={styles.locationIcon}>📍</i> {item.location}
                                </div>
                                <div className={styles.travelDistance}>
                                    距离: {item.distance}km
                                </div>
                            </div>
                            <div className={styles.travelFooter}>
                                <div className={`${styles.travelPrice} ${getPriceVariantClass(index)}`}>
                                    {item.price > 0 ? `¥${item.price}` : '免费'}
                                </div>
                                <div className={styles.travelPurchase}>已售{item.purchaseCount}</div>
                                <button className={styles.travelBookBtn}>立即预订</button>
                            </div>
                        </div>
                    </div>
                ))}
                
                {loading && (
                    <div className={styles.loadingMore}>
                        <div className={styles.loadingSpinner}></div>
                        <span>加载中...</span>
                    </div>
                )}
                
                {travelItems.length >= 20 && (
                    <div className={styles.noMoreData}>
                        已加载全部数据
                    </div>
                )}
            </div>
        </div>
    );
};

export default Travel;